const newsService = require('../services/newsService')

const newsController = {
  async getNews(req, res, next) {
    try {
      let newsList = await newsService.getNews(req.query).find
      newsList = newsList.map(item => ({
        ...item._doc,
        createdAt: item.createdAt?.getTime(),
        updatedAt: item.updatedAt?.getTime(),
      }))
      let total = await newsService.getNews(req.query).count
      res.send({
        code: 200,
        data: {
          newsList,
          total,
        },
        msg: '获取成功',
      })
    } catch (error) {
      res.send({
        code: 400,
        msg: error.message,
      })
    }
  },
  async addNews(req, res, next) {
    try {
      let data = await newsService.addNews(req.body)
      res.send({
        code: 200,
        data,
        msg: '添加成功',
      })
    } catch (error) {
      res.send({
        code: 400,
        msg: error.message,
      })
    }
  },
  async updateNews(req, res, next) {
    try {
      let body = req.body
      let id = body._id
      delete body.id
      let data = await newsService.updateNews(id, body)
      res.send({
        code: 200,
        msg: 'ok',
        data,
      })
    } catch (error) {
      res.send({
        code: 400,
        msg: error.message,
      })
    }
  },
  async deleteNews(req, res, next) {
    try {
      let data = await newsService.deleteNews(req.body.id)
      res.send({
        code: 200,
        msg: 'ok',
        data,
      })
    } catch (error) {
      res.send({
        code: 400,
        msg: error.message,
      })
    }
  },
}

module.exports = newsController
